package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.MemberAttrManager;
import com.fish.anne.model.MemberAttr;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class MemberAttrAction extends BaseAction implements Preparable {
    private MemberAttrManager memberAttrManager;
    private List memberAttrs;
    private MemberAttr memberAttr;
    private Long  attrId;

    public void setMemberAttrManager(MemberAttrManager memberAttrManager) {
        this.memberAttrManager = memberAttrManager;
    }

    public List getMemberAttrs() {
        return memberAttrs;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String memberAttrId = getRequest().getParameter("memberAttr.attrId");
            if (memberAttrId != null && !memberAttrId.equals("")) {
                memberAttr = memberAttrManager.get(new Long(memberAttrId));
            }
        }
    }

    public String list() {
        memberAttrs = memberAttrManager.getAll();
        return SUCCESS;
    }

    public void setAttrId(Long  attrId) {
        this. attrId =  attrId;
    }

    public MemberAttr getMemberAttr() {
        return memberAttr;
    }

    public void setMemberAttr(MemberAttr memberAttr) {
        this.memberAttr = memberAttr;
    }

    public String delete() {
        memberAttrManager.remove(memberAttr.getAttrId());
        saveMessage(getText("memberAttr.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (attrId != null) {
            memberAttr = memberAttrManager.get(attrId);
        } else {
            memberAttr = new MemberAttr();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (memberAttr.getAttrId() == null);

        memberAttrManager.save(memberAttr);

        String key = (isNew) ? "memberAttr.added" : "memberAttr.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}